#!/bin/bash
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/alias.sh"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/conda_run.sh"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/conda_and_pip_settings.sh"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/print_sys_info.sh"

APP_INSTALL_NAME="index-tts2"
APP_TARGET_DIR_NAME="index-tts2"

export CURRENT_APP_PATH="$LMD_APPS_DIR/$APP_TARGET_DIR_NAME"
echo "App Dir: ${CURRENT_APP_PATH}"

cd "$CURRENT_APP_PATH"

if [ -z "$HF_ENDPOINT" ] && [ -n "$HF_MIRROR" ]; then
    export HF_ENDPOINT="$HF_MIRROR"
fi

export GRADIO_TEMP_DIR="$CURRENT_APP_PATH/temp"
CONDA_PREFIX="./venv"

LOCAL_MODEL_DIR="checkpoints"
echo "model dir $LOCAL_MODEL_DIR" 


PORT_PARAM=""
if [ -n "$GRADIO_SERVER_PORT" ]; then
  PORT_PARAM="--port $GRADIO_SERVER_PORT"
fi


echo "use ./venv to start app."
export HF_HOME="$CURRENT_APP_PATH/tmp_hf_home"
export MODELSCOPE_HOME="$CURRENT_APP_PATH/tmp_modelscope_home"
export MODELSCOPE_CACHE="$CURRENT_APP_PATH/tmp_modelscope_cache"

export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True

if [ "$LMD_LAUNCH_APP_MODULE" = "cpu-mode" ]; then
  export CUDA_VISIBLE_DEVICES="-1"
fi

transformers_cache_dir="$CURRENT_APP_PATH/tmp_hf_home_by_modelscope"
campplus_model_dir="$transformers_cache_dir/hub/models--funasr--campplus"

APP_FILE="webui.py"
if [ -d "$campplus_model_dir" ]; then
  echo "found hf models in $transformers_cache_dir"
  export TRANSFORMERS_OFFLINE=1
  export HF_HUB_DISABLE_SYMLINKS=1
  export TRANSFORMERS_CACHE="$transformers_cache_dir/hub"
  export HF_HOME="$transformers_cache_dir"
  cp "$LMD_BASE_INSTALL_SCRIPT_DIR/apps/$APP_INSTALL_NAME/patch_hf.py" "$CURRENT_APP_PATH"
  cp "$LMD_BASE_INSTALL_SCRIPT_DIR/apps/$APP_INSTALL_NAME/run.py" "$CURRENT_APP_PATH"
  APP_FILE="run.py"  
fi

if [ -f /System/Library/CoreServices/SystemVersion.plist ]; then
  echo "macOS. LMD_LOCALE: $LMD_LOCALE"
  if [ "$LMD_LOCALE" = "zhHans" ]; then
    cp "$LMD_BASE_INSTALL_SCRIPT_DIR/apps/$APP_INSTALL_NAME/run_zh.py" "$CURRENT_APP_PATH"
    APP_FILE="run_zh.py"
    cp webui.py webui_zh.py
    sed -i '' 's|language="Auto"|language="zh_CN"|g' webui_zh.py
  fi
fi

conda run -p $CONDA_PREFIX --no-capture-output python $APP_FILE $PORT_PARAM --model_dir $LOCAL_MODEL_DIR --fp16
